<template>
    <div>
        <el-dialog
            v-model="dialogVisible"
            :title="dialogTitle"
            width="600px"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            @close="closeDialog">
            
            <el-form
                ref="formRef"
                :model="formData"
                :rules="rules"
                label-width="100px"
                class="dict-form">
                
                <el-form-item label="所属字典" prop="category_id">
                    <el-select
                        v-model="formData.category_id"
                        placeholder="请选择所属字典"
                        style="width: 100%"
                        clearable>
                        <el-option
                            v-for="category in categoryOptions"
                            :key="category.id"
                            :label="category.name"
                            :value="category.id">
                            <span>{{ category.name }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ category.code }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                
                <el-form-item label="项名称" prop="name">
                    <el-input
                        v-model="formData.name"
                        placeholder="请输入项名称"
                        maxlength="50"
                        show-word-limit
                        clearable>
                    </el-input>
                </el-form-item>
                
                <el-form-item label="数据值" prop="value">
                    <el-input
                        v-model="formData.value"
                        placeholder="请输入数据值"
                        maxlength="100"
                        show-word-limit
                        clearable>
                    </el-input>
                </el-form-item>
                
                <el-form-item label="是否有效" prop="status">
                    <el-switch
                        v-model="formData.status"
                        active-text="启用"
                        inactive-text="禁用">
                    </el-switch>
                </el-form-item>
                
                <el-form-item label="排序" prop="sort">
                    <el-input-number
                        v-model="formData.sort"
                        :min="0"
                        :max="9999"
                        controls-position="right"
                        style="width: 150px">
                    </el-input-number>
                </el-form-item>
                
                <el-form-item label="备注">
                    <el-input
                        v-model="formData.description"
                        type="textarea"
                        :rows="4"
                        placeholder="请输入备注信息"
                        maxlength="200"
                        show-word-limit>
                    </el-input>
                </el-form-item>
            </el-form>
            
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="closeDialog">关闭</el-button>
                    <el-button type="primary" @click="submitForm" :loading="loading">
                        {{ mode === '新增' ? '保存' : '更新' }}
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { apiDictItemAdd, apiDictItemEdit, apiDictCategoryOptions } from '@/api/api'

export default {
    name: 'AddItem',
    
    props: {
        selectedCategory: {
            type: Object,
            default: null
        }
    },
    
    data() {
        return {
            dialogVisible: false,
            dialogTitle: '',
            mode: '新增',
            loading: false,
            currentId: null,
            
            categoryOptions: [],
            
            formData: {
                category_id: null,
                name: '',
                value: '',
                status: true,
                sort: 0,
                description: ''
            },
            
            rules: {
                category_id: [
                    { required: true, message: '请选择所属字典', trigger: 'change' }
                ],
                name: [
                    { required: true, message: '请输入项名称', trigger: 'blur' },
                    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
                ],
                value: [
                    { required: true, message: '请输入数据值', trigger: 'blur' },
                    { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
                ],
                sort: [
                    { required: true, message: '请输入排序', trigger: 'blur' },
                    { type: 'number', min: 0, max: 9999, message: '排序必须在0-9999之间', trigger: 'blur' }
                ]
            }
        }
    },
    
    methods: {
        // 打开弹窗
        open(data, mode) {
            this.dialogVisible = true
            this.mode = mode
            this.dialogTitle = mode + '字典项'
            
            // 获取字典分类选项
            this.getCategoryOptions()
            
            if (mode === '编辑' && data) {
                this.currentId = data.id
                this.formData = {
                    category_id: data.dict_id || data.category_id || null,
                    name: data.item_name || data.name || '',
                    value: data.item_value || data.value || '',
                    status: data.is_active !== undefined ? data.is_active : (data.status !== undefined ? data.status : true),
                    sort: data.sort_order !== undefined ? data.sort_order : (data.sort || 0),
                    description: data.remark || data.description || ''
                }
            } else {
                this.resetForm()
                // 如果有选中的分类，自动设置
                if (this.selectedCategory) {
                    this.formData.category_id = this.selectedCategory.id
                }
            }
        },
        
        // 关闭弹窗
        closeDialog() {
            this.dialogVisible = false
            this.resetForm()
        },
        
        // 重置表单
        resetForm() {
            this.currentId = null
            this.formData = {
                category_id: null,
                name: '',
                value: '',
                status: true,
                sort: 0,
                description: ''
            }
            
            if (this.$refs.formRef) {
                this.$refs.formRef.resetFields()
            }
        },
        
        // 获取字典分类选项
        async getCategoryOptions() {
            try {
                const res = await apiDictCategoryOptions()
                if (res.code === 200) {
                    this.categoryOptions = res.data || []
                }
            } catch (error) {
                console.error('获取字典分类选项失败:', error)
            }
        },
        
        // 提交表单
        submitForm() {
            this.$refs.formRef.validate((valid) => {
                if (valid) {
                    this.loading = true
                    
                    // 转换字段名以匹配后端API
                    const apiData = {
                        dict_id: this.formData.category_id,
                        item_name: this.formData.name,
                        item_value: this.formData.value,
                        sort_order: this.formData.sort,
                        is_active: this.formData.status,
                        remark: this.formData.description || ''
                    }
                    
                    const apiCall = this.mode === '新增' 
                        ? apiDictItemAdd(apiData)
                        : apiDictItemEdit(this.currentId, apiData)
                    
                    apiCall.then(res => {
                        this.loading = false
                        if (res.code === 200 || res.code === 201) {
                            this.$message.success(res.message || `${this.mode}字典项成功`)
                            this.closeDialog()
                            this.$emit('refreshData')
                        } else {
                            this.$message.warning(res.message || `${this.mode}字典项失败`)
                        }
                    }).catch(error => {
                        this.loading = false
                        this.$message.error(`${this.mode}字典项失败: ${error.message || error}`)
                        console.error('API Error:', error)
                    })
                } else {
                    this.$message.warning('请检查表单信息')
                }
            })
        }
    }
}
</script>

<style scoped>
.dict-form {
    padding: 20px 0;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style> 